package org.linlinjava.litemall.admin.web;

import com.google.common.collect.Lists;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.linlinjava.litemall.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.litemall.admin.dto.FormulaDTO;
import org.linlinjava.litemall.admin.dto.FormulaVO;
import org.linlinjava.litemall.admin.dto.MaterialAttribute;
import org.linlinjava.litemall.admin.dto.MaterialVO;
import org.linlinjava.litemall.admin.service.AdminFormulaService;
import org.linlinjava.litemall.admin.util.AdminResponseCode;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.validator.Order;
import org.linlinjava.litemall.core.validator.Sort;
import org.linlinjava.litemall.db.domain.Formula;
import org.linlinjava.litemall.db.domain.FormulaMaterial;
import org.linlinjava.litemall.db.domain.Material;
import org.linlinjava.litemall.db.service.FormulaMaterialService;
import org.linlinjava.litemall.db.service.FormulaService;
import org.linlinjava.litemall.db.service.MaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/admin/formula")
@Validated
public class AdminFormulaController {
    private final Log logger = LogFactory.getLog(AdminFormulaController.class);

    @Autowired
    private FormulaService formulaService;

    @Autowired
    private AdminFormulaService adminFormulaService;

    @Autowired
    private FormulaMaterialService formulaMaterialService;

    @Autowired
    private MaterialService materialService;

    @RequiresPermissions("admin:formula:list")
    @RequiresPermissionsDesc(menu = {"物料管理", "配方管理"}, button = "查询")
    @GetMapping("/list")
    public Object list(String id, String name,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        List<Formula> brandList = formulaService.querySelective(id, name, page, limit, sort, order);
        if (CollectionUtils.isEmpty(brandList)) {
            return ResponseUtil.okList(brandList);
        }
        List<FormulaVO> formulaVOS = Lists.newArrayList();
        for (Formula formula : brandList) {
            Integer formulaId = formula.getId();
            List<FormulaMaterial> formulaMaterials = formulaMaterialService.getByFid(formulaId);
            FormulaVO formulaVO = new FormulaVO();
            formulaVO.setId(formulaId);
            formulaVO.setCode(formula.getCode());
            formulaVO.setName(formula.getName());
            formulaVO.setNumber(formula.getNumber());
            formulaVO.setPrice(formula.getPrice());
            formulaVO.setBrief(formula.getBrief());
            List<MaterialVO> materialVOS = Lists.newArrayList();
            for (FormulaMaterial formulaMaterial : formulaMaterials) {
                Integer materialId = formulaMaterial.getmId();
                MaterialVO materialVO = new MaterialVO();
                materialVO.setId(materialId);
                materialVO.setAmount(formulaMaterial.getAmount());
                Material material = materialService.getById(materialId);
                materialVO.setCode(material.getCode());
                materialVO.setName(material.getName());
                materialVO.setName(material.getName());
                materialVO.setUnit(material.getUnit());
                materialVO.setPrice(material.getPrice());
                BigDecimal totalPrice = material.getPrice().multiply(formulaMaterial.getAmount());
                materialVO.setTotalPrice(totalPrice);
                materialVOS.add(materialVO);
            }
            formulaVO.setMaterialVOS(materialVOS);
            formulaVOS.add(formulaVO);
        }
        return ResponseUtil.okList(formulaVOS);
    }


    @RequiresPermissions("admin:formula:simpleList")
    @RequiresPermissionsDesc(menu = {"物料管理", "配方管理"}, button = "简单查询")
    @GetMapping("/simpleList")
    public Object simpleList() {
        List<Formula> brandList = formulaService.all();
        if (CollectionUtils.isEmpty(brandList)) {
            return ResponseUtil.okList(brandList);
        }
        return ResponseUtil.ok(brandList);
    }

    @RequiresPermissions("admin:formula:create")
    @RequiresPermissionsDesc(menu = {"物料管理", "配方管理"}, button = "添加")
    @PostMapping("/create")
    public Object create(@RequestBody FormulaDTO brand) {
        if (brand == null) {
            return ResponseUtil.badArgument();
        }
        Object result = adminFormulaService.addOne(brand);
        return result;
    }

    @RequiresPermissions("admin:formula:read")
    @RequiresPermissionsDesc(menu = {"物料管理", "配方管理"}, button = "详情")
    @GetMapping("/read")
    public Object read(@NotNull Integer formulaId) {
        FormulaDTO formulaDTO = new FormulaDTO();
        Formula formula = formulaService.findById(formulaId);
        formulaDTO.setFormula(formula);

        List<MaterialAttribute> attributes = new ArrayList<>();
        List<FormulaMaterial> formulaMaterials = formulaMaterialService.getByFid(formulaId);
        if(CollectionUtils.isEmpty(formulaMaterials)){
            formulaDTO.setAttributes(attributes);
        }else {
            for (FormulaMaterial formulaMaterial : formulaMaterials) {
                Integer materialId = formulaMaterial.getmId();
                MaterialAttribute materialVO = new MaterialAttribute();
                materialVO.setMaterialId(materialId);
                materialVO.setAmount(formulaMaterial.getAmount());
                Material material = materialService.getById(materialId);
                materialVO.setMaterialName(material.getName());
                materialVO.setUnit(material.getUnit());
                attributes.add(materialVO);
            }
            formulaDTO.setAttributes(attributes);
        }


        return ResponseUtil.ok(formulaDTO);
    }

    @RequiresPermissions("admin:formula:changeMaterialNum")
    @RequiresPermissionsDesc(menu = {"物料管理", "获取配方列表"}, button = "修改")
    @PostMapping("/changeMaterialNum")
    public Object changeMaterialNum(@RequestBody Formula param) {
        FormulaDTO formulaDTO = new FormulaDTO();
        Formula formula = formulaService.findById(param.getId());
        formulaDTO.setFormula(formula);
        Integer number = param.getNumber();
        Integer baseNum = formula.getNumber();
        if(number%baseNum!=0) {
            return ResponseUtil.fail(AdminResponseCode.SYSTEM_ERROR,"数量必须是配方数量的整数倍");
        }
        int dum = number / baseNum;
        List<MaterialAttribute> attributes = new ArrayList<>();
        List<FormulaMaterial> formulaMaterials = formulaMaterialService.getByFid(param.getId());
        if(CollectionUtils.isEmpty(formulaMaterials)){
            formulaDTO.setAttributes(attributes);
        }else {
            for (FormulaMaterial formulaMaterial : formulaMaterials) {
                Integer materialId = formulaMaterial.getmId();
                MaterialAttribute materialVO = new MaterialAttribute();
                materialVO.setMaterialId(materialId);
                materialVO.setAmount(formulaMaterial.getAmount().multiply(new BigDecimal(String.valueOf(dum))));
                Material material = materialService.getById(materialId);
                materialVO.setMaterialName(material.getName());
                materialVO.setUnit(material.getUnit());
                attributes.add(materialVO);
            }
            formulaDTO.setAttributes(attributes);
        }
        return ResponseUtil.ok(formulaDTO);
    }

    @RequiresPermissions("admin:formula:update")
    @RequiresPermissionsDesc(menu = {"物料管理", "配方管理"}, button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody FormulaDTO brand) {
        if (brand == null) {
            return ResponseUtil.badArgument();
        }
        Object result = adminFormulaService.updateOne(brand);
        return result;
    }

    @RequiresPermissions("admin:formula:delete")
    @RequiresPermissionsDesc(menu = {"物料管理", "配方管理"}, button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody Formula brand) {
        Integer id = brand.getId();
        if (id == null) {
            return ResponseUtil.badArgument();
        }
        formulaService.deleteById(id);
        return ResponseUtil.ok();
    }
}
